//
//  WeAuctionMapController.m
//  WeGalaxy
//
//  Created by Zheng on 2017/7/11.
//  Copyright © 2017年 Zheng. All rights reserved.
//

#import "WeAuctionMapController.h"
#import "WeAuctionMapSelectView.h"
#import "WeAuctionMapCell.h"

static NSString *kWeAuctionMapCell_ID = @"kWeAuctionMapCell_ID";

@interface WeAuctionMapController () <BMKMapViewDelegate,BMKLocationServiceDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) BMKMapView *mapView;
@property (nonatomic, strong) BMKLocationService *locService;
@property (nonatomic, strong) UIButton *locationBtn;
@property (nonatomic, strong) WeAuctionMapSelectView *selectView;
@property (nonatomic, strong) NSMutableArray<BMKAnnotationView *> *annotataionsArr;
@property (nonatomic) NSInteger annotationIndex;
@property (nonatomic, strong) UICollectionView *infoView;
@property (nonatomic, assign) CGPoint endOffSet;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic) BOOL isFirstTapInfo;

@property (nonatomic, strong) NSMutableArray<UIImageView *> *images;

@end

@implementation WeAuctionMapController

#pragma mark - 加载数据
- (void)loadData {
    
    [self addAnnotationWithSelected:NO withTitle:@"AAA" withlatitude:39.949293 withlongitude:116.441885];
    [self addAnnotationWithSelected:NO withTitle:@"BBB" withlatitude:39.933293 withlongitude:116.446885];
    [self addAnnotationWithSelected:NO withTitle:@"CCC" withlatitude:39.923293 withlongitude:116.436885];
    [self addAnnotationWithSelected:NO withTitle:@"DDD" withlatitude:39.933293 withlongitude:116.456885];

}

- (void)addAnnotationWithSelected:(BOOL)selected
                        withTitle:(NSString *)title
                     withlatitude:(CGFloat)latitude
                    withlongitude:(CGFloat)longitude {
    
    CLLocationCoordinate2D l =CLLocationCoordinate2DMake(latitude, longitude);
    BMKPointAnnotation *a = [[BMKPointAnnotation alloc] init];
    a.coordinate = l;
    a.title = title;
    [_mapView addAnnotation:a];

    
}

#pragma mark - 按钮点击事件
- (void)locationBtnAction:(UIButton *)sender {
    [_locService startUserLocationService];

}

#pragma mark - BMKMapViewDelegate
- (void)mapview:(BMKMapView *)mapView onDoubleClick:(CLLocationCoordinate2D)coordinate {
    if (_isFirstTapInfo) {
        _isFirstTapInfo = NO;
        
        CGFloat height = 150;
        
        [UIView animateWithDuration:kANIMATION_DURATION animations:^{
            _infoView.frame = CGRectMake(0, kSCREENH_HEIGHT, kSCREEN_WIDTH, height);
            _locationBtn.frame = (CGRect){10,kSCREENH_HEIGHT-180,40,40};
        }];
        
        [_images enumerateObjectsUsingBlock:^(UIImageView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [UIView animateWithDuration:kMASK_Duration animations:^{
                obj.frame = (CGRect){5,5,50,50};
            }];
        }];
    }
}

- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation {
    
    BMKAnnotationView *aView = [[BMKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"kWeAuctionMapController_ID"];
    [aView setImage:kIMAGE(@"bw_dtz")];
    aView.annotation = annotation;
    aView.canShowCallout = NO;
//    aView.backgroundColor = [UIColor whiteColor];
    
    UIImageView *iconImgv = [[UIImageView alloc] init];
    iconImgv.frame = (CGRect){5,5,50,50};
    iconImgv.backgroundColor = [UIColor orangeColor];
    [aView addSubview:iconImgv];
    
    [_images addObject:iconImgv];
    [_annotataionsArr addObject:aView];
    
    return aView;
}

- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view {
//    kCX_LOG(@"%@",view.annotation.title);
    
    CLLocationCoordinate2D loc = view.annotation.coordinate;
    BMKCoordinateSpan span;
    span.latitudeDelta = 0.05;
    span.longitudeDelta = 0.05;
    
    BMKCoordinateRegion viewRegion;
    viewRegion.center = loc;
    viewRegion.span = span;
    
    BMKCoordinateRegion adjustedRegion = [_mapView regionThatFits:viewRegion];
    [_mapView setRegion:adjustedRegion animated:YES];
    
    __block NSUInteger selectIndex;
    
    [_annotataionsArr enumerateObjectsUsingBlock:^(BMKAnnotationView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if([obj.annotation.title isEqualToString:view.annotation.title]) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:idx inSection:0];
            [_infoView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
            selectIndex = idx;
        }
    }];
    
    [_images enumerateObjectsUsingBlock:^(UIImageView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx == selectIndex) {
            [UIView animateWithDuration:kMASK_Duration animations:^{
                obj.frame = (CGRect){0,0,60,60};
            }];
        } else {
            [UIView animateWithDuration:kMASK_Duration animations:^{
                obj.frame = (CGRect){5,5,50,50};
            }];
        }
    }];
    
    if (!_isFirstTapInfo) {
        
        CGFloat height = 150;
        
        [UIView animateWithDuration:kANIMATION_DURATION animations:^{
            _infoView.frame = CGRectMake(0, kSCREENH_HEIGHT-288, kSCREEN_WIDTH, height);
            _locationBtn.frame = (CGRect){10,kSCREENH_HEIGHT-335,40,40};
        }];
        
        _isFirstTapInfo = YES;
    }
}

- (void)mapView:(BMKMapView *)mapView onClickedMapBlank:(CLLocationCoordinate2D)coordinate {
    
    if (_isFirstTapInfo) {
        _isFirstTapInfo = NO;
        
        CGFloat height = 150;
        
        [UIView animateWithDuration:kANIMATION_DURATION animations:^{
            _infoView.frame = CGRectMake(0, kSCREENH_HEIGHT, kSCREEN_WIDTH, height);
            _locationBtn.frame = (CGRect){10,kSCREENH_HEIGHT-180,40,40};
        }];
    
        [_images enumerateObjectsUsingBlock:^(UIImageView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [UIView animateWithDuration:kMASK_Duration animations:^{
                obj.frame = (CGRect){5,5,50,50};
            }];
        }];
        
    }
}


#pragma mark - BMKLocationServiceDelegate
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    
    if (_mapView) {
        //更新位置
        [_mapView updateLocationData:userLocation];
        
        CLLocationCoordinate2D loc = userLocation.location.coordinate;
        BMKCoordinateSpan span;
        span.latitudeDelta = 0.05;
        span.longitudeDelta = 0.05;
        
        BMKCoordinateRegion viewRegion;
        viewRegion.center = loc;
        viewRegion.span = span;
        
        BMKCoordinateRegion adjustedRegion = [_mapView regionThatFits:viewRegion];
        [_mapView setRegion:adjustedRegion animated:YES];

        [_locService stopUserLocationService];
    }
    
}

#pragma mark - 子视图
- (BMKMapView *)mapView {
    if (!_mapView) {
        //初始化BMKLocationService
        _locService = [[BMKLocationService alloc]init];
        _locService.delegate = self;
        //启动LocationService
        [_locService startUserLocationService];
        
        BMKLocationViewDisplayParam *param = [[BMKLocationViewDisplayParam alloc] init];
        param.isRotateAngleValid = false;// 跟随态旋转角度是否生效
        param.isAccuracyCircleShow = false;// 精度圈是否显示
        param.locationViewImgName = @"icon_center_point";// 定位图标名称
        param.locationViewOffsetX = 0;//定位图标偏移量(经度)
        param.locationViewOffsetY = 0;// 定位图标偏移量(纬度)
        
        _mapView = [[BMKMapView alloc] init];
        _mapView.showsUserLocation = YES;
        _mapView.userTrackingMode = BMKUserTrackingModeFollow;
        _mapView.showMapScaleBar = YES;
        _mapView.delegate = self;
        _mapView.zoomLevel = 15;
        
        [_mapView updateLocationViewWithParam:param];
    }
    return _mapView;
}

- (UIButton *)locationBtn {
    if (!_locationBtn) {
        _locationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _locationBtn.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.85];
        _locationBtn.frame = (CGRect){10,kSCREENH_HEIGHT-180,40,40};
        [_locationBtn setImage:kIMAGE(@"we_loc") forState:UIControlStateNormal];
        [_locationBtn addTarget:self action:@selector(locationBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _locationBtn;
}

- (WeAuctionMapSelectView *)selectView {
    if (!_selectView) {
        _selectView = [[WeAuctionMapSelectView alloc] init];
        _selectView.frame = (CGRect){0,0,kSCREEN_WIDTH,38};
        _selectView.titles = @[@"全部",@"美食",@"影城",@"地铁",@"公交站",@"景点"];
    }
    return _selectView;
}

- (UICollectionView *)infoView {
    if (!_infoView) {
        
        CGFloat height = 150;
        CGFloat width = kSCREEN_WIDTH-20;
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.itemSize = CGSizeMake(width, height);
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.minimumLineSpacing = 10;
        flowLayout.minimumInteritemSpacing = 0;
        
        _infoView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, kSCREENH_HEIGHT, kSCREEN_WIDTH, height) collectionViewLayout:flowLayout];
        _infoView.delegate = self;
        _infoView.dataSource = self;
        _infoView.showsHorizontalScrollIndicator = NO;
        _infoView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0];
        [_infoView registerClass:[WeAuctionMapCell class] forCellWithReuseIdentifier:kWeAuctionMapCell_ID];
    }
    return _infoView;
}

- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] init];
        _bottomView.backgroundColor = [UIColor whiteColor];
    }
    return _bottomView;
}

#pragma mark - collectionview datasource && delegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _annotataionsArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    WeAuctionMapCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kWeAuctionMapCell_ID forIndexPath:indexPath];
    
    cell.describeLbl.text = [NSString stringWithFormat:@"描述+++%ld",indexPath.item];
    cell.priceLbl.text = [NSString stringWithFormat:@"¥ %ld",(indexPath.item+1)*480];
    
    return cell;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 10, 0, 10);
}

#pragma mark - scrollview delegate
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    _endOffSet = scrollView.contentOffset;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (scrollView.contentOffset.x > 0) {
        NSInteger item = (NSInteger)scrollView.contentOffset.x / (NSInteger)(355/375.*kSCREEN_WIDTH);
        item = (scrollView.contentOffset.x > _endOffSet.x) ? item+1 : item;
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:item inSection:0];
        if (item < _annotataionsArr.count) {
            [(UICollectionView *)scrollView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
            NSLog(@"----%ld",item);
            
            [_images enumerateObjectsUsingBlock:^(UIImageView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (idx == item) {
                    [UIView animateWithDuration:kMASK_Duration animations:^{
                        obj.frame = (CGRect){0,0,60,60};
                    }];
                } else {
                    [UIView animateWithDuration:kMASK_Duration animations:^{
                        obj.frame = (CGRect){5,5,50,50};
                    }];
                }
            }];

            CLLocationCoordinate2D loc = _annotataionsArr[item].annotation.coordinate;
            BMKCoordinateSpan span;
            span.latitudeDelta = 0.05;
            span.longitudeDelta = 0.05;
            
            BMKCoordinateRegion viewRegion;
            viewRegion.center = loc;
            viewRegion.span = span;
            
            BMKCoordinateRegion adjustedRegion = [_mapView regionThatFits:viewRegion];
            [_mapView setRegion:adjustedRegion animated:YES];
            
        }
    }
}


- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.x > 0) {
        NSInteger item = (NSInteger)scrollView.contentOffset.x / (NSInteger)(355/375.*kSCREEN_WIDTH);
        item = (scrollView.contentOffset.x > _endOffSet.x) ? item+1 : item;
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:item inSection:0];
        if (item < _annotataionsArr.count) {
            [(UICollectionView *)scrollView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
        }
    }
}

#pragma mark - 视图生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    
    _annotataionsArr = [NSMutableArray new];
    _annotationIndex = 0;
    _isFirstTapInfo = NO;
    _images = [NSMutableArray new];
    
    self.title = @"拍卖";
    
    [self.view addSubview:self.mapView];
    [_mapView addSubview:self.locationBtn];
    [_mapView addSubview:self.selectView];
    [_mapView addSubview:self.infoView];
    [_mapView addSubview:self.bottomView];
    
    [_mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.left.equalTo(self.view);
        make.bottom.mas_equalTo(-kTAB_BAR_Height);
    }];

    [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.view);
        make.height.mas_equalTo(kTAB_BAR_Height);
    }];
    
    [self loadData];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放

}

-(void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
}

#pragma mark - 内存警告
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
